/**
 * 增加代理
 * @param proxy
 */
this.add = function(proxy){
    proxy.weight = proxy.resTime;
    var regionId = proxy.regionId;
    if (typeof this.proxylist[regionId] === "undefined"){
        this.proxylist[regionId] = new Array();
    }
    //判断是否存在
    var hasProxy = this.find(proxy);
    if(hasProxy){ //存在代理，主要处理的是权重
        var oldProxy = this.proxylist[hasProxy.regionId][hasProxy.index];
        if(oldProxy.weight - oldProxy.resTime > 0){
            proxy.weight = proxy.weight + oldProxy.weight - oldProxy.resTime;
        }
        this.proxylist[regionId][hasProxy.index] = proxy;
    }else{
        this.proxylist[regionId].push(proxy);
    }
}

this.find = function(proxy){
    for(var i in this.proxylist){
        var len = this.proxylist[i].length;

        for(var j=0;j<len;j++){
            var p = this.proxylist[i][j];
            if(p.host == proxy.host && p.port==proxy.port){
                return {"regionId":i,"index":j}
            }
        }//end for
    }
    return null;
}

/**
 * 删除代理
 * @param proxy
 */
this.del = function(proxy){
    var hasProxy = this.find(proxy);
    if(hasProxy){
        this.proxylist[hasProxy.regionId].splice(hasProxy.index,1);
    }
}

this.getList = function(){
    return this.proxylist;
}

/**
 * 获取一个指定地区代理
 * @param regionId
 */
this.get = function(regionId){
    if(this.proxylist[regionId]==undefined){
        return null;
    }
    this.sort(regionId);
    var proxy = this.proxylist[regionId][0];
    if( proxy == undefined){
        return null;
    }else{
        this.incrWeight(proxy);
        var newProxy = this.util.clone(proxy);

        //给这次的获取做一个标示
        newProxy.useid = this.util.s8();

        //超时，自动释放
        var tmpThis = this;
        this.useidList[newProxy.useid] = setTimeout(function(){
            console.log("自动释放ip"+newProxy.host+" "+newProxy.useid);
            tmpThis.release(newProxy);
        },this.autoReleaseTime);

        return newProxy;
    }
}


this.release = function(proxy){
    if(this.useidList[proxy.useid] != undefined){
        clearTimeout(this.useidList[proxy.useid]);
        delete this.useidList[proxy.useid];
        this.decrWeight(proxy);
    }
}

/**
 * 降低权重
 * @param proxy
 */
this.decrWeight = function(proxy){
    var regionId = proxy.regionId;
    var hasProxy = this.find(proxy);
    if(hasProxy){
        var proxy = this.proxylist[regionId][hasProxy.index];
        if(proxy.weight>proxy.resTime){
            proxy.weight -= this.useOneWeight;
        }
    }
}

/**
 * 提高权重
 * @param proxy
 */
this.incrWeight = function(proxy){
    var regionId = proxy.regionId;
    var hasProxy = this.find(proxy);
    if(hasProxy){
        this.proxylist[regionId][hasProxy.index]["weight"] += this.useOneWeight;
    }
}

this.sort = function(regionId){
    if(this.proxylist[regionId] instanceof Array){
        this.proxylist[regionId].sort(this.util.compareObjectFn("weight"));
    }
}